/*
 * @Author: hongbin
 * @Date: 2021-11-23 22:34:17
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-24 08:15:46
 * @Description: 控制面板
 */
import { FC, ReactElement, MouseEventHandler } from "react";
import styled from "styled-components";
import { Button } from "../BUI";
import { ThemeBgc } from "../BUI/View/ThemeView";

interface IProps {
  clearCanvas: () => void;
}

const panelDown: MouseEventHandler<HTMLDivElement> = e => {
  const panel = e.currentTarget.parentElement as HTMLElement;
  const { pageX, pageY } = e;
  const { clientWidth, clientHeight } = document.body;

  const decompose = panel.style.transform.match(/translate\((\S+), (\S+)\)/);
  // 加上原来位移
  let prevLateX = 0;
  let prevLateY = 0;
  if (Array.isArray(decompose) && decompose[2]) {
    prevLateX = parseFloat(decompose[1]);
    prevLateY = parseFloat(decompose[2]);
  }

  const containerOffsetTop = panel.parentElement!.offsetTop;

  const move = (e: MouseEvent) => {
    e.preventDefault();

    const { offsetWidth, offsetHeight, offsetLeft, offsetTop } = panel;
    let x = e.pageX - pageX + prevLateX;
    let y = e.pageY - pageY + prevLateY;

    const maxW = offsetWidth + offsetLeft + x;
    const minW = offsetLeft + x;
    const maxH = offsetHeight + offsetTop + y;
    const minH = offsetTop + y;

    if (maxW > clientWidth - 10) x = 10;
    if (minW < 10) x = offsetWidth - clientWidth + 20;
    if (maxH > clientHeight - containerOffsetTop) y = 10;
    if (minH < 10) y = -offsetTop + 10;

    panel.style["transform"] = `translate(${x}px,${y}px)`;
  };
  document.addEventListener("mousemove", move);

  document.addEventListener("mouseleave", () => {
    document.removeEventListener("mousemove", move);
  });
  document.addEventListener("mouseup", () => {
    document.removeEventListener("mousemove", move);
  });
};

const Panel: FC<IProps> = ({ clearCanvas }): ReactElement => {
  return (
    <Wrap>
      <DragWrap onMouseDown={panelDown} />
      <div>
        加粗&nbsp;
        <input type="checkbox" />
        <Button onClick={clearCanvas}>清除画布</Button>
      </div>
    </Wrap>
  );
};

export default Panel;

const DragWrap = styled.div`
  width: 100%;
  height: 1rem;
  background: inherit;
  position: absolute;
  cursor: move;
  left: 0;
  top: 0;
  transition: background 0.3s linear;
  :hover {
    background: #ccc;
  }
  :active {
    background: #333;
  }
`;

const Wrap = styled.div`
  position: absolute;
  overflow: hidden;
  padding: 1rem;
  bottom: 1rem;
  right: 1rem;
  border-radius: 12px;
  box-shadow: 2px 2px 20px 1px #ccc;
  width: 20rem;
  height: 20rem;
  ${ThemeBgc};
`;
